package boot.spring.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	// 该对象用来支持 password 模式
    @Autowired
    AuthenticationManager authenticationManager;
    
    // 该对象用来将令牌信息存储到Redis中
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
 
    // 该对象将为刷新token提供支持
    @Autowired
    UserDetailsService userDetailsService;
    
    @Autowired
	BCryptPasswordEncoder encoder;
 
    // 指定密码的加密方式
    @Bean
    BCryptPasswordEncoder passwordEncoder() {
        // 使用BCrypt强哈希函数加密方案（密钥迭代次数默认为10）
        return new BCryptPasswordEncoder();
    }
 
    // 配置 password 授权模式
    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        clients.inMemory()
            .withClient("web")
            .authorizedGrantTypes("implicit","client_credentials","authorization_code","password", "refresh_token") //授权模式为password和refresh_token两种
//            .authorizedGrantTypes("authorization_code","refresh_token") 
            .accessTokenValiditySeconds(1800) // 配置access_token的过期时间
            .resourceIds("rid") //配置资源id
            .scopes("server")
            .autoApprove(false)
            .secret(encoder.encode("1234"))
            //这个相当于是client的域名,重定向给code的时候会跳转这个域名
            .redirectUris("http://www.baidu.com");
    }
 
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory)) //配置令牌的存储（这里存放在内存中）
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }
 
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.allowFormAuthenticationForClients()//允许form表单客户端认证,允许客户端使用client_id和client_secret获取token
        .checkTokenAccess("isAuthenticated()")     //通过验证返回token信息
        .tokenKeyAccess("permitAll()")            // 获取token请求不进行拦截
        .passwordEncoder(encoder);
    }
}
